<!DOCTYPE HTML>
<html>
<head>
<title>点击拖拽</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style type="text/css">
    #div1{
        position: absolute;
        width: 200px;
        height: 200px;
        background: pink;
    }
</style>
<script type="text/javascript">
    window.onload = function(){
    var moveBox = document.getElementById('div1');
    var windowH = window.innerHeight,
        windowW = window.innerWidth;
    // 当鼠标在moveBox里面按下时
    moveBox.onmousedown = function(event){
        event = event || window.event;
        var distanceX = event.clientX - this.offsetLeft,
            distanceY = event.clientY - this.offsetTop;

        // 当鼠标在document任意位置时，连续触发    
        document.onmousemove = function(event_2){
            event_2 = event_2 || window.event;
            var left = event_2.clientX - distanceX,
                top = event_2.clientY - distanceY;
            if (left < 0) left = 0;
            if (top < 0) top = 0;
            if (left > windowW - moveBox.offsetWidth) left = windowW - moveBox.offsetWidth;
            if (top > windowH - moveBox.offsetHeight) top = windowH - moveBox.offsetHeight;
            moveBox.style.left = left + 'px';
            moveBox.style.top = top + 'px';
        }

        // 当鼠标离开时,移除鼠标移动事件；
        document.onmouseup = function(){
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
}
</script>
</head>
<body>
    <div id="div1"></div>
</body>
</html>